package sync;

public class unsafeBuyTricks {
    public static void main(String[] args) {
        BuyTricks buyTricks = new BuyTricks();
        new Thread(buyTricks, "张三").start();
        new Thread(buyTricks, "李四").start();
        new Thread(buyTricks, "黄牛").start();
    }
}
class BuyTricks implements Runnable{
    private int tricks = 10;
    private boolean flag = true;
    @Override
    public void run() {
        //买票
        while (flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //买票
    //加synchronized安全
    public synchronized void buy() throws InterruptedException {
        Thread.sleep(200);
        //判断票数
        if (tricks<=0) {
            this.flag = false;
            return;
        }
        System.out.println(Thread.currentThread().getName()+"买到"+tricks--);
    }
}